package org.wanho.servlet;

import com.alibaba.fastjson.JSON;
import org.wanho.constant.ResponseStatusConstant;
import org.wanho.entity.User;
import org.wanho.util.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Author：汤小洋
 * Date：2023-04-28 13:46
 * Description：<描述>
 */
@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // resp.setContentType("text/html;charset=utf8");
        // resp.setContentType("text/plain;charset=utf8");
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();


        // 将对象转换为JSON格式的字符串
        User user = new User(101,"徐嵩",20,new Date());
        // String str = JSON.toJSONString(user);
        // System.out.println(str);

        // List<User> list = new ArrayList<>();
        // list.add(new User(101,"徐嵩",20,new Date()));
        // list.add(new User(102,"许嵩",29,new Date()));
        // list.add(new User(103,"李嵩",21,new Date()));
        // list.add(new User(104,"王嵩",18,new Date()));
        // out.print(JSON.toJSONString(list));

        // 将JSON格式字符串转换对象
        // User u = JSON.parseObject(str, User.class);
        // System.out.println(u);

        /**
         * 响应自定义的对象
         */
        ResponseResult result = new ResponseResult();
        result.setStatus(ResponseStatusConstant.SUCCESS);
        result.setMessage("success");
        result.setData(user);

        out.print(JSON.toJSONString(result));

        out.close();
    }
}
